package apptoko.com.fragment;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.FullScreenshotImageActivity;
import apptoko.com.ItemBrokerActivity;
import apptoko.com.event.Event.GetNewDesFailEvent;
import apptoko.com.event.Event.GetNewDescriptionSuccessEvent;
import apptoko.com.model.ContentItemInfo;
import apptoko.com.model.ContentItemInfo.RelatedItem;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.ScaleImageView;

import com.androidquery.AQuery;
import apptoko.com.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusOneButton;

import de.greenrobot.event.EventBus;

public class DetailsFragment extends BaseFragment implements  ConnectionCallbacks, OnConnectionFailedListener, OnClickListener {
	
	private ContentItemInfo item;
	private AQuery aq;
//	private RelatedItemAdapter adapter;
	private Typeface robotoBoldCon;
	private String contentType;
	private String videoLink;
	public static final int REQUEST_CODE_RESOLVE_ERR = 9000;
    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private PlusOneButton mPlusOneButton;
    private String description;
    private ConnectionResult mConnectionResult;
    //private ToggleButton btnLike;
   // private BackgroundTasks bgTask;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.layout_details, null);
//		btnLike = (ToggleButton) mParent.findViewById(R.id.btn_like);
//		btnLike.setOnClickListener(this);
		mPlusOneButton = (PlusOneButton) mParent.findViewById(R.id.plus_one_button);
		LinearLayout scrContainer = (LinearLayout) mParent.findViewById(R.id.screenshot_container);
		aq = new AQuery(mParent);
		int price1 = item.getVersionList().get(0).getPrice1();
		int price2 = item.getVersionList().get(0).getPrice2();
		String price = "";
		if(price1 == 0 && price2 == 0){
			price = String.format(getResources().getString(R.string.detail_price), getResources().getString(R.string.free));
			aq.id(R.id.details_tym).gone();
		} else if(price1 != 0 && price2 == 0){
			price = String.format(getResources().getString(R.string.detail_price), String.valueOf(price1));
			aq.id(R.id.details_tym).image(R.drawable.tym_green).visible();
		} else if(price1 == 0 && price2 != 0){
			price = String.format(getResources().getString(R.string.detail_price), String.valueOf(price2));
			aq.id(R.id.details_tym).image(R.drawable.tym_purple).visible();
		}
		aq.id(R.id.dummy_desc).typeface(robotoBoldCon);
		Log.e("requirement","requirement:"+item.requirement);
		if(!TextUtils.isEmpty(item.requirement)){
			aq.id(R.id.requirement).text("REQUIREMENT: "+item.requirement).visibility(View.VISIBLE);
			aq.id(R.id.requirement).textColor(Color.RED);
		}
		if(!contentType.equalsIgnoreCase("android")){
			aq.id(R.id.price_version).text("- " + item.getVersionList().get(0).getName());
		} else {
			aq.id(R.id.price_version).text("");
		}
		aq.id(R.id.details_price).text(Html.fromHtml(price));
		aq.id(R.id.details_views).text(Html.fromHtml(String.format(getResources().getString(R.string.download_count), Utils.formatNumber("###,###,###", item.getTotalViews()))));
		aq.id(R.id.details_size).text(Html.fromHtml(String.format(getResources().getString(R.string.size), item.getSize())));//Utils.printSize(item.getSize()))));
		aq.id(R.id.details_version).text(Html.fromHtml(String.format(getResources().getString(R.string.newest_version), item.getVersionList().get(0).getName())));
		aq.id(R.id.details_rating).rating(item.getSumRate()!=0?item.getTotalRate()/item.getSumRate():0);
		aq.id(R.id.details_comments).text(Html.fromHtml(String.format(getResources().getString(R.string.total_comment), Utils.formatNumber("###,###,###", item.getTotalComment()))));
		String description = item.getDescription().replace("\\n", "<br/>").replace("\n", "<br/>");
		aq.id(R.id.details_desc).text(Html.fromHtml(description));
		this.description=description;
		final List<String> screenShots = item.getScreenShots();
		videoLink = item.getVideoLink();
		if(!TextUtils.isEmpty(videoLink)){
			View video = inflater.inflate(R.layout.video_image, null);

			ScaleImageView front = (ScaleImageView) video.findViewById(R.id.front_layer);
			front.setImageResource(R.drawable.ic_video);

			video.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent youtube = new Intent(Intent.ACTION_VIEW);
					youtube.setData(Uri.parse(videoLink));
					startActivity(youtube);
				}
				});
			scrContainer.addView(video);
		}
		for(int i=0; i<screenShots.size(); i++){
			View image = inflater.inflate(R.layout.screenshot_image, null);
			final AQuery scrAq = new AQuery(image);
			scrAq.id(R.id.index).text(i + "");
			scrAq.id(R.id.screenshot_image).clicked(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String[] imageUrls = screenShots.toArray(new String[screenShots.size()]);
					Intent full = new Intent(getActivity(), FullScreenshotImageActivity.class);
					full.putExtra(Constants.IMAGES, imageUrls);
					full.putExtra(Constants.IMAGE_POSITION, Integer.parseInt(scrAq.id(R.id.index).getText().toString()));
					startActivity(full);
				}
			});
			if(scrAq.id(R.id.screenshot_image).getCachedFile(screenShots.get(i))!=null){
				scrAq.id(R.id.screenshot_image).image(scrAq.id(R.id.screenshot_image).getCachedFile(screenShots.get(i)),0);
				Log.e("","loadss f cached");
			}else{
				scrAq.id(R.id.screenshot_image).image(screenShots.get(i), false, true, 0, 0, null, AQuery.FADE_IN);
			}
			
			scrContainer.addView(image);
		}
//		adapter = new RelatedItemAdapter(mContext, R.layout.related_item, item.getRelatedItems());
//		aq.id(R.id.related_list).adapter(adapter).itemClicked(this);
		aq.id(R.id.dummy_related).typeface(robotoBoldCon).visible();
		return mParent;
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		item = (ContentItemInfo) getArguments().getSerializable(Constants.ITEM_INFO);
		robotoBoldCon = Typeface.createFromAsset(mContext.getAssets(), mContext.getResources().getString(R.string.roboto_bold_condensed));
		contentType = item.getApplicationType();
		mPlusClient = new PlusClient.Builder(mContext, this, this).clearScopes().build();
	//	bgTask = new BackgroundTasks(mContext);
		mConnectionProgressDialog = new ProgressDialog(mContext);
		mConnectionProgressDialog.setMessage("Signing in...");
		EventBus.getDefault().register(this);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
//		checkLikedOrNot();
//		loadNumberOfLikes();
	}
	
//	@Override
//	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
//		// TODO Auto-generated method stub
//		RelatedItem item = (RelatedItem) parent.getItemAtPosition(pos);
//		Intent i = new Intent(getActivity(), ItemBrokerActivity.class);
//		i.putExtra(Constants.SLUG, item.getSlug());
//		i.putExtra(Constants.PREVIOUS_SCREEN, "/Details");
//		i.putExtra(Constants.KEY_REFERER, "related");
//		i.putExtra(Constants.STORE_KEY, getArguments().getString(Constants.STORE_KEY));
//		i.putExtra(Constants.FROM, getArguments().getInt(Constants.FROM));
//		startActivity(i);
//	}
	
	@Override
	public void onStart() {
		super.onStart();
		mPlusClient.connect();
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(item.getApplicationType().equalsIgnoreCase("android")){
			mPlusOneButton.initialize(mPlusClient, Constants.APPTOKO_PC + item.getPackageName(), REQUEST_CODE_RESOLVE_ERR);
		} else if(item.getApplicationType().equalsIgnoreCase("ebook")){
			mPlusOneButton.initialize(mPlusClient, Constants.EBOOK_PC + item.getAppstorevnId(), REQUEST_CODE_RESOLVE_ERR);
		} else if(item.getApplicationType().equalsIgnoreCase("comic")){
			mPlusOneButton.initialize(mPlusClient, Constants.COMIC_PC + item.getAppstorevnId(), REQUEST_CODE_RESOLVE_ERR);
		} else {
			mPlusOneButton.initialize(mPlusClient, Constants.MOVIE_ROOT + item.getAppstorevnId(), REQUEST_CODE_RESOLVE_ERR);
		}
	}
	
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mPlusClient.disconnect();
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		Log.e("onConnectionFailed","onConnectionFailed mPlusClient");
		if (result.hasResolution()) {
            try {
                    result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
            } catch (SendIntentException e) {
                    mPlusClient.connect();
            }
    }
		mConnectionResult=result;
	}
//	@Override
//	public void onActivityResult(int requestCode, int responseCode, Intent intent) {
//		// TODO Auto-generated method stub
//		super.onActivityResult(requestCode,responseCode,intent);
//		 if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == Activity.RESULT_OK) {
//		        mConnectionResult = null;
//		        mPlusClient.connect();
//		    }
//	}
	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		Log.e("onConnected","onConnected mPlusClient");
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
//		case R.id.btn_like:
//			String facebookToken = mContext.getSharedPreferences(getString(R.string.fb_app_id), 0).getString("accessToken", "");
//			bgTask.like(Constants.APPSTOREVN_PC + item.getPackageName(), facebookToken);
//			break;

		default:
			break;
		}
	}
	
//	private void loadNumberOfLikes(){
//		bgTask.getLikeNumber(Constants.APPSTOREVN_PC + item.getPackageName());
//	}
//	
//	private void checkLikedOrNot(){
//		String facebookToken = mContext.getSharedPreferences(getString(R.string.fb_app_id), 0).getString("accessToken", "");
//		bgTask.likedOrNot(Constants.APPSTOREVN_PC + item.getPackageName(), facebookToken);
//	}
//	
//	public void onEventMainThread(Event.GetLikeNumberEvent e){
//		aq.id(R.id.number_of_like).text(Utils.formatNumber("###,###,###", (int)e.getLikes()));
//	}
//	
//	public void onEventMainThread(Event.LikedEvent e){
//		btnLike.setChecked(true);
//		btnLike.setEnabled(false);
//	}
//	
//	public void onEventMainThread(Event.NotLikedEvent e){
//		btnLike.setChecked(false);
//		btnLike.setEnabled(false);
//	}
//	
	public void onEventMainThread(GetNewDescriptionSuccessEvent e){
//		if(description.equalsIgnoreCase(e.des)){
//			Toast.makeText(mContext, "Description is the same!", Toast.LENGTH_LONG).show();
//			aq.id(R.id.details_desc).text(Html.fromHtml(description));
//		}else{
//			Toast.makeText(mContext, "Description is different", Toast.LENGTH_LONG).show();
//		}
		Toast.makeText(mContext, "Msg: "+e.des, Toast.LENGTH_LONG).show();
	}
	
	public void onEventMainThread(GetNewDesFailEvent e){
				Toast.makeText(mContext, "send check description failed", Toast.LENGTH_LONG).show();
	}
//	
//	public void onEventMainThread(LikeFailEvent e){

//		btnLike.setEnabled(true);
//	}

}
